<template>
  <div>
    <div style="padding-top: 5px">
      <h3 style="display: inline-block; margin-left: 45%">简历编辑区</h3>
      <el-button
        style="margin-left: 35%"
        type="primary"
        round
        size="small"
        @click="previewResume"
      >
        预览简历</el-button
      >
    </div>

    <el-divider></el-divider>
    <el-form
      ref="resumeForm"
      :model="resumeForm"
      label-width="100px"
      style="margin-top: 20px"
      :rules="resumeFormRules"
      @keydown.enter="submitForm('resumeForm')"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="学号" prop="studentId">
            <el-input
              v-model="resumeForm.studentId"
              :disabled="description == '管理员' ? false : true"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="resumeForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生日">
            <el-date-picker
              v-model="resumeForm.birthday"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="resumeForm.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="期望工作城市">
            <el-cascader
              size="large"
              :options="regionData"
              v-model="resumeForm.addressId"
              @change="handleChange(resumeForm.addressId)"
              :props="{ checkStrictly: true }"
              placeholder="省 / 市 / 区"
            >
            </el-cascader> </el-form-item
        ></el-col>
        <el-col :span="8">
          <el-form-item label="期望职业类别">
            <el-select
              v-model="resumeForm.expectedPositionCategory"
              placeholder="请选择岗位类别"
              filterable
              ref="jobCategorySelect"
              @change="
                jobCategorySelectChange(resumeForm.expectedPositionCategory)
              "
            >
              <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="期望职位">
            <el-select
              v-model="resumeForm.expectedPosition"
              placeholder="请选择期望职位"
              filterable
              @change="jobNameSelectChange(resumeForm.expectedPosition)"
            >
              <el-option
                v-for="item in jobNames"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="期望薪资">
            <el-select
              v-model="resumeForm.expectedSalary"
              placeholder="请选择期望薪资"
              filterable
              ref="jobCategorySelect"
            >
              <el-option
                v-for="item in salaries"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号码">
            <el-input v-model="resumeForm.mobile"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮箱">
            <el-input v-model="resumeForm.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学历" prop="education">
            <el-select
              v-model="resumeForm.education"
              placeholder="请选择要求学历"
            >
              <el-option
                v-for="item in educations"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学校">
            <el-input v-model="resumeForm.school"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="专业">
            <el-select v-model="resumeForm.major" placeholder="请选择专业">
              <el-option
                v-for="item in majorListForIdAndName"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="毕业时间">
            <el-date-picker
              v-model="resumeForm.graduationTime"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="证书">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="resumeForm.certificate"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="技能">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="resumeForm.skill"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="实习经验">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="resumeForm.internshipExperience"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="项目经验">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="resumeForm.projectExperience"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="resumeForm.experience"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="自我评价">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 6 }"
              placeholder="请输入内容"
              v-model="resumeForm.selfEvaluation"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div style="text-align: center">
            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm('resumeForm')"
                v-loading.fullscreen.lock="fullscreenLoading"
                >确认</el-button
              >
              <el-button type="warning" @click="resetForm('resumeForm')"
                >重置</el-button
              >
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { reqQueryResumeById } from '@/views/Custom/ResumeMng/api/ResumeMngApi';
import { regionData, CodeToText } from 'element-china-area-data';
import { mapGetters } from 'vuex';
import { Message } from 'element-ui';
export default {
  name: 'ResumeEdit',
  props: ['isEdit', 'resumeRowInfo'],
  data() {
    var validatedStudentIdIsExisting = async (rule, value, callback) => {
      if (!value) {
        return callback([new Error('请输入学号')]);
      }
      if (value != this.loginId && this.description == '学生用户') {
        return callback([new Error('请输入自己的学号！！！')]);
      }
      // 判断学号是否有效
      let result = await this.$store.dispatch(
        'StudentMng/checkStudentIdIsExisting',
        this.loginId
      );
      if (!result.flag) {
        return callback([new Error('学号不存在')]);
      }

      //   }
    };
    return {
      fullscreenLoading: false,
      regionData: regionData,
      jobNames: [],
      resumeForm: {},
      educations: [],
      salaries: [],
      imageUrl: '',
      isStudentUser: false,
      resumeFormRules: {
        studentId: [
          {
            required: true,
            validator: validatedStudentIdIsExisting,
            trigger: ['blur'],
          },
        ],
        name: [
          {
            required: true,
            message: '请输入学生姓名',
            trigger: ['blur'],
          },
        ],
        sex: [
          {
            required: true,
            message: '请选择学生性别',
            trigger: ['change'],
          },
        ],
        education: [
          {
            required: true,
            message: '请选择学历',
            trigger: ['change'],
          },
        ],
      },
    };
  },
  computed: {
    // 登录用户
    ...mapGetters(['name', 'description', 'loginId', 'avatar']),
    // 岗位
    ...mapGetters('PostPostingMng', ['jobIPage', 'jobList']),
    // 企业
    ...mapGetters('CompanyMng', ['companyIdAndNameAndCodeList']),
    // 工作分类
    ...mapGetters('JobCategoryMng', ['categories', 'jobNameAndIdList']),
    // 数据字典
    ...mapGetters('DictMng', ['educationList', 'salaryList']),
    // 院系管理---专业编号与名称列表
    ...mapGetters('AcademyMng', ['majorListForIdAndName']),
  },
  watch: {
    // 薪水
    salaryList() {
      this.$set(this, 'salaries', this.salaryList);
    },
    // 学历
    educationList() {
      this.$set(this, 'educations', this.educationList);
    },
    //对应类别下的 工作名称
    jobNameAndIdList() {
      this.$set(this, 'jobNames', this.jobNameAndIdList);
    },
    'resumeForm.expectedPositionCategory'(newValue, oldValue) {
      if (!this.isEdit && !this.isStudentUser) {
        this.resumeForm.expectedPosition = '';
      }
      if (newValue) {
        // this.jobNames = [];
        // 发送请求
        this.$store.dispatch('JobCategoryMng/getIdAndNameList', newValue);
      }
    },
  },
  mounted() {
    // 获取学历列表
    this.getEducationList();
    // 获取专业列表
    this.getMajorList();
    // 获取职位分类列表
    this.getCategories();
    // 获取薪水列表
    this.getSalaries();
    // 通过简历列表页跳转来后,简历信息回显
    if (this.resumeRowInfo) {
      this.resumeForm = {
        ...this.resumeRowInfo,
      };
    }
    switch (this.description) {
      case '学生用户':
        this.getResumeInfo();
        break;
    }
  },
  methods: {
    // 首次加载从数据库里查询简历
    getResumeInfo() {
      reqQueryResumeById(this.loginId).then((res) => {
        let addressId = [];
        if (res.data.resumeInfo) {
          let arr = res.data.resumeInfo.expectedCityId.split('-');
          arr.forEach((item) => {
            addressId.push(item);
          });
        }

        if (!res.data.flag) {
          this.resumeForm = {
            ...res.data.resumeInfo,
            addressId,
          };
          this.isStudentUser = true;
        } else {
          this.initData();
        }
      });
    },

    // 表单初值
    async initData() {
      // 判断学号是否有效
      let result = await this.$store.dispatch(
        'StudentMng/checkStudentIdIsExisting',
        this.loginId
      );
      // 登录的用户编号;
      let { name, gender, majorId } = result.student;
      // 判断用户输入的是否是自己的学号
      // 显示学生姓名、性别、专业
      this.$set(this.resumeForm, 'name', name);
      this.$set(this.resumeForm, 'sex', gender);
      this.$set(this.resumeForm, 'major', majorId);
      this.$set(this.resumeForm, 'studentId', this.loginId);
      this.$set(this.resumeForm, 'shcool', '湖北工程学院');
      this.$set(this.resumeForm, 'education', 30003);
    },
    // 检测简历是否编辑
    checkEidtResume() {
      reqQueryResumeById(this.loginId).then((res) => {
        if (res.data.flag) {
          this.$router.push({
            name: 'resumeEdit',
          });
        } else {
          this.$router.push({
            name: 'resumetemplate',
            params: {
              resumeRowInfo: { ...res.data.resumeInfo, avatar: this.avatar },
            },
          });
        }
      });
    },
    // 预览简历
    previewResume() {
      this.checkEidtResume();
    },

    // 头像上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 绑定函数重新加载一下组件
    jobNameSelectChange(val) {
      this.$forceUpdate();
      let obj = this.jobNames.find((item) => {
        return item.id == val;
      });
      this.resumeForm.expectedPositionName = obj.name;
    },
    // 获取薪资列表
    async getSalaries() {
      // 查询薪资id
      let dict = await this.$store.dispatch('DictMng/getDictIdByName', '薪水');
      if (dict && dict.id) {
        this.$store.dispatch('DictMng/getSalaryListByParentId', dict.id);
      } else {
        this.$message({
          message: '返回的薪水编号为空',
          type: 'error',
          duration: 1 * 1000,
        });
      }
    },
    // 获取职位分类列表
    getCategories() {
      this.$store.dispatch('JobCategoryMng/getCategories');
    },
    // 获取学历列表
    async getEducationList() {
      // 查询学历id
      let dict = await this.$store.dispatch('DictMng/getDictIdByName', '学历');
      if (dict && dict.id) {
        this.$store.dispatch('DictMng/getEduListByParentId', dict.id);
      } else {
        this.$message({
          message: '返回的学历编号为空',
          type: 'error',
          duration: 1 * 1000,
        });
      }
    },
    // 获取专业编号与名称列表
    getMajorList() {
      this.$store.dispatch('AcademyMng/getMajorListForIdAndName');
    },
    // 城市选择
    handleChange(addressId) {
      var loc = '';
      // for (let i = 0; i < this.selectedJob.length; i++) {
      //   // this.$refs["cascader"].getCheckedNodes()[0].label 获取选中的label
      //   loc += this.$refs['cascader'].getCheckedNodes()[0].label;
      // }
      var locId = '';
      for (let i = 0; i < addressId.length; i++) {
        loc += CodeToText[addressId[i]] + '/';
        locId += addressId[i] + '-';
      }
      loc = loc.substring(0, loc.length - 1);
      locId = locId.substring(0, locId.length - 1);
      //工作地点字符串
      this.$set(this.resumeForm, 'expectedCity', loc);
      //工作地点编号
      this.$set(this.resumeForm, 'expectedCityId', locId);
    },
    // 类别选择
    jobCategorySelectChange(val) {
      let obj = this.categories.find((item) => {
        return item.id == val;
      });
      this.resumeForm.expectedPositionCategoryName = obj.name;
    },
    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            // 接收返回的结果
            let result = {};
            if (!this.isEdit && !this.isStudentUser) {
              let paramsArray = [];
              let params = {
                ...this.resumeForm,
              };
              paramsArray.push(params);
              // 发送请求
              result = await this.$store.dispatch(
                'ResumeMng/batchAddResume',
                paramsArray
              );
              this.getResumeInfo();
            } else {
              result = await this.$store.dispatch(
                'ResumeMng/editResume',
                this.resumeForm
              );
              this.$message({
                message: result.message,
                type: 'success',
                duration: 2 * 1000,
              });
              if (!this.isStudentUser) {
                // 更新操作结束，跳转会简历列表
                this.$router.replace({
                  name: 'resumeList',
                });
              }
            }
            this.$message({
              message: result.message,
              type: 'success',
              duration: 2 * 1000,
            });
          } catch (error) {
            Message.error(error || 'Has Error');
          } finally {
            this.fullscreenLoading = false; // 关闭遮罩层
            this.isAdd = false; // 重置表单状态
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style></style>
